package com.lancoo.znbkxx.teacher.utils

import android.content.Context
import android.media.MediaRecorder
import android.os.Environment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.lebanban.mp3library.MP3Recorder
import java.io.File
import java.io.IOException
import java.lang.Exception

/**
 * @author : wealive
 * @date   : 2020/4/9 19:31
 * @desc   :
 */
class AudioRecord(val context: Context) : DefaultLifecycleObserver {
    private lateinit var mr: MP3Recorder
    private lateinit var soundFile: File

    //开始录制
    fun startRecord() {
        val dir = File(context.getExternalFilesDir(""), "sounds")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        try {
            soundFile =
                    File(dir, System.currentTimeMillis().toString() + ".mp3")
            if (!soundFile.exists()) {
                try {
                    soundFile.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            mr = MP3Recorder(soundFile)
//            mr.setMaxDuration(60000)
//            mr.setAudioSource(MediaRecorder.AudioSource.MIC) //音频输入源
//            mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB) //设置输出格式
//            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB) //设置编码格式
//            mr.setOutputFile(soundFile.absolutePath)
//            mr.prepare()
            mr.start() //开始录制
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    //停止录制，资源释放
    fun stopRecord() {
        try {
            mr.stop()
//            mr.release()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun getPath(): String {
        return soundFile.absolutePath
    }

    override fun onResume(owner: LifecycleOwner) {
        stopRecord()
    }

    override fun onPause(owner: LifecycleOwner) {
        stopRecord()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        stopRecord()
    }

    override fun onStop(owner: LifecycleOwner) {
        stopRecord()
    }
}